<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { DnsNsListItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import {
  getDnsAuthorityNameserverApi,
  postDnsAuthorityNameserverApi,
  updateDnsAuthorityNameserverApi,
} from '@/apis/modules/dns'

interface IProp {
  record?: DnsNsListItem
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits<IEmits>()
interface IEmits {
  (e: 'reload', flag: boolean): void
}
const visible = defineModel<boolean>('visible', { required: true })
const title = computed(() => (props.record?.id ? '编辑地址' : '新增地址'))
const formRef = ref<FormInstance>()
const formState = reactive({
  hostname: '',
  remark: '',
})
const rules: Record<string, FieldRule> = {
  hostname: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('地址不能为空')
      }
      if (!regexpMap.domain.test(value)) {
        return callback('地址格式不正确')
      }
      callback()
    },
  },
}
const loading = ref(false)
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  loading.value = true
  const apiPath = props.record?.id
    ? updateDnsAuthorityNameserverApi
    : postDnsAuthorityNameserverApi
  return apiPath(formState)
    .then(() => {
      Message.success('操作成功')
    })
    .finally(() => (loading.value = false))
}
async function getDetail() {
  loading.value = true
  await getDnsAuthorityNameserverApi({ id: props.record?.id })
    .then((res) => {
      Object.assign(formState, {
        ...omit(res, ['created_at', 'updated_at']),
      })
    })
    .finally(() => (loading.value = false))
}
function handleOpen() {
  if (props.record?.id)
    getDetail()
}
function handleClose() {
  formRef.value?.resetFields()
  emit('reload', !!props.record?.id)
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    ok-text="保存"
    :loading="loading"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleOpen"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="地址"
        field="hostname"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.hostname"
          :max-length="255"
          show-word-limit
          placeholder="请输入地址"
        />
      </a-form-item>
      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped></style>
